import menuFunction from '@/js/MenuFunction'
import ConstDef from '@/js/ConstDef'
import nvService from '@/api/NvService'
import cacheManage from '@/cache/CacheManage'
class FilterDialogUtils {
  async filter(event, refDialog) {
    function setValues(selectNv, currentNv) {
      for (const fdInfo of expression.fdInfos) {
        currentNv[fdInfo.fdName] = selectNv[fdInfo.sourceFdName];
      }
    }
    function singleChooseCb(selectNv) {
      const overwrite = expression.overwrite;
      if (overwrite) {
        const nv = event.fvData.getNv();
        setValues(selectNv, nv);
      } else {
        const commonInfo = cacheManage.getDefaultCommonInfo();
        const nvMsg = nvService.initNv(commonInfo, event.fvData.nd.ndCode);
        if (!nvMsg.success) return;
        const nv = nvMsg.value;
        event.fvData.getNvs().push(nv);
        setValues(selectNv, nv);
      }
    }
    function multipleChooseCb(selectNvs) {
      for (const selectNv of selectNvs) {
        singleChooseCb(selectNv);
      }
    }
    const fdLayout = event.fvData.fdLayout;
    const str = fdLayout.expression;
    const expression = JSON.parse(str);
    const msg = await menuFunction.getFilterConfig(ConstDef.FILTER_FUNCTION, expression.filterDefCode);
    if (!msg.success) return;
    const config = msg.value;
    config.action.autoFilter = true;
    if (expression.chooseType === 'single') {
      refDialog.showSingleChoose(config, singleChooseCb);
    } else if (expression.chooseType === 'multiple') {
      refDialog.showSingleChoose(config, multipleChooseCb);
    } else if (expression.chooseType === 'immediate') {
      refDialog.showSingleChoose(config, singleChooseCb);
    }
  }
}

const filterDialogUtils = new FilterDialogUtils();
export default filterDialogUtils;
